﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using DiagramDesigner.Common.Helpers;

namespace DiagramDesigner.Common.Controls
{
    public class DesignerItem : ContentControl
    {
        #region IsSelected dependency property

        public static readonly DependencyProperty IsSelectedProperty =
            DependencyProperty.Register("IsSelected", typeof (bool), typeof (DesignerItem),
                                        new PropertyMetadata(default(bool)));

        public bool IsSelected
        {
            get { return (bool) GetValue(IsSelectedProperty); }
            set { SetValue(IsSelectedProperty, value); }
        }

        #endregion

        private bool _isSelectedPrevious;
        private bool _dragTookPlace;

        public DesignerItem()
        {
            
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            DesignerCanvas canvas = VisualTreeHelper.GetParent(this) as DesignerCanvas;
            if (canvas == null) return;            

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _dragTookPlace = true;
                canvas.DeselectAll(this);
            }
        }

        protected override void OnMouseUp(MouseButtonEventArgs e)
        {
            base.OnMouseUp(e);
            DesignerCanvas canvas = VisualTreeHelper.GetParent(this) as DesignerCanvas;
            if (canvas == null) return;

            if (_dragTookPlace)
            {
                IsSelected = true;
                _dragTookPlace = false;
                return;
            }

            if (_isSelectedPrevious)
            {
                CanvasHelper.Canvas.DeselectAll();
            }
            else
            {
                IsSelected = true;
                CanvasHelper.Canvas.DeselectAll(this);

            }
            Focus();   
        }

        protected override void OnMouseDown(MouseButtonEventArgs e)
        {
            base.OnMouseDown(e);
            _isSelectedPrevious = IsSelected;
        }
    }
}
